package com.leyou.item.service;

import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exceptions.LyException;
import com.leyou.common.utils.BeanHelper;
import com.leyou.item.dto.CategoryDTO;
import com.leyou.item.entity.Category;
import com.leyou.item.mapper.CategoryMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;

@Service
public class CategoryService {

    @Autowired
    private CategoryMapper categoryMapper;

    /**
     * 分页查询商品分类
     * @param pid
     * @return
     */
    public List<CategoryDTO> queryListByParentId(Long pid) {
        //查询条件，mapper会把对象中的非空属性作为查询条件
        Category t = new Category();
        t.setParentId(pid);
        List<Category> categories = categoryMapper.select(t);
        //判断结果是否存在
        if(CollectionUtils.isEmpty(categories)){
            throw new LyException(ExceptionEnum.CATEGORY_NOT_FOUND);
        }

        //使用自定义工具类，把Category集合转为DTO的集合
        return BeanHelper.copyWithCollection(categories,CategoryDTO.class);
    }

    /**
     * 根据品牌id查询商品信息
     * @param brandId
     * @return
     */
    public List<CategoryDTO> queryListByBrandId(Long brandId) {
        List<Category> list = categoryMapper.queryByBrandId(brandId);

        //判断结果
        if(CollectionUtils.isEmpty(list)){
            throw new LyException(ExceptionEnum.CATEGORY_NOT_FOUND);
        }
        //使用自定义工具类，把Category几个转为DTO的集合
        return BeanHelper.copyWithCollection(list,CategoryDTO.class);
    }

    /**
     * 根据品牌id集合ids 查询商品信息
     * @param ids
     * @return
     */
    public List<CategoryDTO> queryCategoryByIds(List<Long> ids) {
        List<Category> categories = categoryMapper.selectByIdList(ids);
        if (CollectionUtils.isEmpty(categories)){
            //找不到，返回404
            throw new LyException(ExceptionEnum.CATEGORY_NOT_FOUND);
        }
        return BeanHelper.copyWithCollection(categories,CategoryDTO.class);
    }
}
